package com.jyx.manage_media.service;

import com.jyx.framework.domain.media.MediaFile;
import com.jyx.framework.domain.media.request.QueryMediaFileRequest;
import com.jyx.framework.model.response.CommonCode;
import com.jyx.framework.model.response.QueryResponseResult;
import com.jyx.framework.model.response.QueryResult;
import com.jyx.manage_media.dao.MediaFileRepository;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

@Service
public class MediaFileService {

    private static Logger LOGGER = LoggerFactory.getLogger(MediaFileService.class);
    @Autowired
    MediaFileRepository mediaFileRepository;

    /**
     * 媒资管理分页查询
     * @param page
     * @param size
     * @param queryMediaFileRequest
     * @return
     */
    public QueryResponseResult findList(int page, int size, QueryMediaFileRequest queryMediaFileRequest) {
        MediaFile mediaFile = new MediaFile();
        if(queryMediaFileRequest == null){
            queryMediaFileRequest = new QueryMediaFileRequest();
        }
        //contains:模糊匹配    exact：精准匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                                    .withMatcher("tag",ExampleMatcher.GenericPropertyMatchers.contains())
                                    .withMatcher("fileOriginalName",ExampleMatcher.GenericPropertyMatchers.contains())
                                    .withMatcher("processStatus",ExampleMatcher.GenericPropertyMatchers.exact());
        if(StringUtils.isNotEmpty(queryMediaFileRequest.getTag())){
            mediaFile.setTag(queryMediaFileRequest.getTag());
        }
        if(StringUtils.isNotEmpty(queryMediaFileRequest.getFileOriginalName())){
            mediaFile.setFileOriginalName(queryMediaFileRequest.getFileOriginalName());
        }
        if(StringUtils.isNotEmpty(queryMediaFileRequest.getProcessStatus())){
            mediaFile.setProcessStatus(queryMediaFileRequest.getProcessStatus());
        }
        Example<MediaFile> mediaFileExample = Example.of(mediaFile, matcher);
        page = page - 1 ;
        PageRequest pageRequest = PageRequest.of(page, size);
        Page<MediaFile> mediaFilePage = mediaFileRepository.findAll(mediaFileExample, pageRequest);
        QueryResult<MediaFile> mediaFileQueryResult = new QueryResult<>();
        mediaFileQueryResult.setList(mediaFilePage.getContent());
        mediaFileQueryResult.setTotal(mediaFilePage.getTotalElements());
        return new QueryResponseResult(CommonCode.SUCCESS,mediaFileQueryResult);
    }
}
